package ym.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import ym.mapper.*;
import ym.pojo.*;

import java.util.Date;
import java.util.List;

@DubboService
public class PatientServiceImpl implements PatientService {
    //    @Autowired
//    IChatAssistant iChatAssistant;
    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private NutritionPlanService nutritionPlanService;
    @Autowired
    private NutritionPlanMapper nutritionPlanMapper;
    @Autowired
    private MealPlanMapper mealPlanMapper;
    @Autowired
    private EnteralNutritionPlanMapper enteralNutritionPlanMapper;
    @Autowired
    private ParenteralNutritionPlanMapper parenteralNutritionPlanMapper;

    @Override
    public void add(Patient patient) {
        patientMapper.insert(patient);
    }

    @Override
    public void update(Patient patient) {
        patientMapper.updateById(patient);
    }

    @Override
    public void delete(Integer id) {
        patientMapper.deleteById(id);
        //删除患者的营养计划
        nutritionPlanService.deleteByPatientId(id);
    }

    @Override
    public Patient findById(Integer id) {
        return patientMapper.selectById(id);
    }

    @Override
    public List<Patient> findAll() {
        return patientMapper.selectList(null);
    }

    @Override
    public Page<Patient> search(String search, int page, int size) {
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        if (search != null) {
            queryWrapper.like("patientName", search);
        }
        return patientMapper.selectPage(new Page(page, size), queryWrapper);
    }


    /**
     * NRS-2002评估【模拟测试版】
     *
     * @return
     */
    @Override
    public String nrs2002Assessment(Integer id) {
        //获取患者信息
        Patient patient = patientMapper.selectById(id);
        //1.评估时间
        patient.setAssessmentDate(String.valueOf(new Date().getTime()));
        //2.评估结果
        String assessmentResult = "";
        // 根据患者疾病严重程度给予相应分数
        int diseaseSeverityScore = getDiseaseSeverityScore(patient);
        // 根据体重减少比例、BMI值等因素给予相应分数
        int nutritionalStatusScore = getNutritionalStatusScore(patient);
        //根据年龄获取分数
        int ageScore = patient.getPatientAge() > 70 ? 1 : 0;
        //3.NRS评分
        int totalScore = diseaseSeverityScore + nutritionalStatusScore + ageScore;
        if (totalScore >= 3) {
            assessmentResult = "存在营养风险";
        } else {
            assessmentResult = "营养风险较低";
        }
        patient.setPatientNRS(String.valueOf(totalScore));
        patient.setAssessmentResult(assessmentResult);
        patientMapper.updateById(patient);
        return String.valueOf(totalScore);
    }


    private static int getDiseaseSeverityScore(Patient patient) {
        // 根据患者疾病严重程度给予相应分数，这里简单示例，实际需更详细判断
        if (patient.getDisease().equals("癌症") || patient.getDisease().equals("严重烧伤")) {
            return 3;
        } else if (patient.getDisease().equals("肺炎") || patient.getDisease().equals("糖尿病并发症")) {
            return 2;
        } else {
            return 1;
        }
    }

    private static int getNutritionalStatusScore(Patient patient) {
        // 根据体重减少比例、BMI值等因素给予相应分数，这里简单示例
        double bmi = patient.getWeight() / (patient.getHeight() * patient.getHeight());
        if (bmi < 18.5) {
            return 3;
        } else if (bmi >= 18.5 && bmi < 24) {
            return 2;
        } else {
            return 1;
        }
    }


    /**
     * MUST评估【模拟测试版】
     *
     * @return
     */
    @Override
    public String mustAssessment(Integer id) {
        //获取患者信息
        Patient patient = patientMapper.selectById(id);
        //1.评估时间
        patient.setAssessmentDate(String.valueOf(new Date().getTime()));
        //2.评估结果
        String assessmentResult = "";
        int bmiScore = getBMIScore(patient);
        // 计算体重分
        int weightLossScore = getWeightLossScore(patient);
        // 计算疾病分
        int reducedFoodIntakeScore = getReducedFoodIntakeScore(patient);
        //3.MUST评分
        int totalScore = bmiScore + weightLossScore + reducedFoodIntakeScore;
        if (totalScore >= 2) {
            assessmentResult = "存在营养风险";
        } else {
            assessmentResult = "营养风险较低";
        }
        patient.setPatientMUST(String.valueOf(totalScore));
        patient.setAssessmentResult(assessmentResult);
        patientMapper.updateById(patient);
        return String.valueOf(totalScore);
    }

    private static int getBMIScore(Patient patient) {
        double bmi = patient.getWeight() / (patient.getHeight() * patient.getHeight());
        if (bmi < 18.5) {
            return 2;
        } else {
            return 0;
        }
    }

    private static int getWeightLossScore(Patient patient) {
        // 假设这里简单判断体重在过去3个月是否减少超过10%，实际需更准确数据
        boolean hasWeightLoss = false;
        // 这里应该从数据库或其他记录获取准确的历史体重数据来判断
        if (hasWeightLoss) {
            return 2;
        } else {
            return 0;
        }
    }

    private static int getReducedFoodIntakeScore(Patient patient) {
        // 假设根据患者疾病情况判断是否因疾病导致进食减少，实际需详细判断
        boolean reducedFoodIntake = false;
        // 这里应该根据患者具体情况判断
        if (reducedFoodIntake) {
            return 2;
        } else {
            return 0;
        }
    }


    /**
     * NSR营养风险筛查与评估[外置ai版]
     *
     * @return
     */
    @Override
    public void nrs2002AssessmentWebAi(Integer patientId,String totalScore,String assessmentResult) {
        Patient patient = patientMapper.selectById(patientId);
        patient.setAssessmentDate(String.valueOf(new Date().getTime()));
        patient.setPatientNRS(totalScore);
        patient.setAssessmentResult(assessmentResult);
        patientMapper.updateById(patient);
    }
    /**
     * MUST营养风险筛查与评估[外置ai版]
     *
     * @return
     */
    @Override
    public void mustAssessmentWebAi(Integer patientId,String totalScore,String assessmentResult) {
        Patient patient = patientMapper.selectById(patientId);
        patient.setAssessmentDate(String.valueOf(new Date().getTime()));
        patient.setPatientNRS(totalScore);
        patient.setAssessmentResult(assessmentResult);
        patientMapper.updateById(patient);
    }

    /**
     * 生成计划【模拟测试版】
     */
    @Override
    public void generatePlan(Integer id) {
        Patient patient = patientMapper.selectById(id);
        String assessmentResult = patient.getAssessmentResult();
        if (assessmentResult.equals("存在营养风险")) {
            // 根据患者具体情况生成更详细的营养计划，这里简单示例,建议使用ai实现
            //1.营养计划
            NutritionPlan nutritionPlan = new NutritionPlan();
            nutritionPlan.setPlanName("健康营养计划");
            nutritionPlan.setNutritionPlanExecutionStatus("进行中");
            nutritionPlan.setGoal("通过合理饮食和锻炼，恢复身体健康水平");
            nutritionPlan.setDailyProtein("2500");
            nutritionPlan.setDailyCarbohydrates("150");
            nutritionPlan.setDailyCalories("300");
            nutritionPlan.setDailyFat("70");
            nutritionPlan.setPatientId(id);
            int nutritionPlanId = nutritionPlanMapper.insert(nutritionPlan);
            //2.膳食方案
            MealPlan mealPlan1 = new MealPlan();
            mealPlan1.setMealType("早餐");
            mealPlan1.setMealFoods("燕麦粥1碗、水煮蛋3个、低脂牛奶1杯（约 250 毫升）");
            mealPlan1.setNutritionPlanId(nutritionPlanId);
            mealPlanMapper.insert(mealPlan1);
            MealPlan mealPlan2 = new MealPlan();
            mealPlan1.setMealType("午餐");
            mealPlan1.setMealFoods("糙米饭 200 克、香煎鸡胸肉 200 克、清炒西兰花 200 克");
            mealPlan1.setNutritionPlanId(nutritionPlanId);
            mealPlanMapper.insert(mealPlan2);
            MealPlan mealPlan3 = new MealPlan();
            mealPlan1.setMealType("晚餐");
            mealPlan1.setMealFoods("红薯 200 克、清蒸鱼 200 克、凉拌菠菜 150 克");
            mealPlan1.setNutritionPlanId(nutritionPlanId);
            mealPlanMapper.insert(mealPlan3);
            //3.肠内营养方案
            EnteralNutritionPlan enteralNutritionPlan = new EnteralNutritionPlan();
            enteralNutritionPlan.setFormulaType("整蛋白型配方");
            enteralNutritionPlan.setVolume("1500");
            enteralNutritionPlanMapper.insert(enteralNutritionPlan);
            //4.肠外营养方案
            ParenteralNutritionPlan parenteralNutritionPlan = new ParenteralNutritionPlan();
            parenteralNutritionPlan.setNutrientComponents("氨基酸、葡萄糖、中长链脂肪乳、多种维生素、微量元素");
            parenteralNutritionPlan.setInfusionRate("50");
            parenteralNutritionPlanMapper.insert(parenteralNutritionPlan);
            //5.患者的治疗阶段
            patient.setTreatmentStage(3);
            patientMapper.updateById(patient);
        } else {
            // 根据患者具体情况生成更详细的营养计划，这里简单示例,建议使用ai实现
            //1.营养计划
            NutritionPlan nutritionPlan = new NutritionPlan();
            nutritionPlan.setPlanName("均衡营养计划");
            nutritionPlan.setNutritionPlanExecutionStatus("进行中");
            nutritionPlan.setGoal("通过合理饮食和锻炼，均衡营养");
            nutritionPlan.setDailyProtein("2300");
            nutritionPlan.setDailyCarbohydrates("120");
            nutritionPlan.setDailyCalories("290");
            nutritionPlan.setDailyFat("60");
            nutritionPlan.setPatientId(id);
            int nutritionPlanId = nutritionPlanMapper.insert(nutritionPlan);
            //2.膳食方案
            MealPlan mealPlan1 = new MealPlan();
            mealPlan1.setMealType("早餐");
            mealPlan1.setMealFoods("燕麦粥1碗、低脂牛奶1杯（约 250 毫升）");
            mealPlan1.setNutritionPlanId(nutritionPlanId);
            mealPlanMapper.insert(mealPlan1);
            MealPlan mealPlan2 = new MealPlan();
            mealPlan1.setMealType("午餐");
            mealPlan1.setMealFoods("糙米饭 200 克、香煎鸡胸肉 200 克、清炒西兰花 200 克");
            mealPlan1.setNutritionPlanId(nutritionPlanId);
            mealPlanMapper.insert(mealPlan2);
            MealPlan mealPlan3 = new MealPlan();
            mealPlan1.setMealType("晚餐");
            mealPlan1.setMealFoods("红薯 200 克、凉拌菠菜 150 克");
            mealPlan1.setNutritionPlanId(nutritionPlanId);
            mealPlanMapper.insert(mealPlan3);
            //3.肠内营养方案
            EnteralNutritionPlan enteralNutritionPlan = new EnteralNutritionPlan();
            enteralNutritionPlan.setFormulaType("半蛋白型配方");
            enteralNutritionPlan.setVolume("1500");
            enteralNutritionPlanMapper.insert(enteralNutritionPlan);
            //4.肠外营养方案
            ParenteralNutritionPlan parenteralNutritionPlan = new ParenteralNutritionPlan();
            parenteralNutritionPlan.setNutrientComponents("氨基酸、葡萄糖、中长链脂肪乳、多种维生素、微量元素");
            parenteralNutritionPlan.setInfusionRate("30");
            parenteralNutritionPlanMapper.insert(parenteralNutritionPlan);
            //5.患者的治疗阶段
            patient.setTreatmentStage(3);
            patientMapper.updateById(patient);
        }


    }

    @Override
    public Integer generatePlanAiForNutritionPlan(NutritionPlan nutritionPlan) {
        nutritionPlanMapper.insert(nutritionPlan);
        return nutritionPlan.getNutritionPlanId();
    }

    @Override
    public Integer generatePlanAiForMealPlan(MealPlan mealPlan) {
        mealPlanMapper.insert(mealPlan);
        return mealPlan.getMealPlanId();
    }

    @Override
    public Integer generatePlanAiForEnteralNutritionPlan(EnteralNutritionPlan enteralNutritionPlan) {
        enteralNutritionPlanMapper.insert(enteralNutritionPlan);
        return enteralNutritionPlan.getEnteralNutritionPlanId();
    }

    @Override
    public Integer generatePlanAiForParenteralNutritionPlan(ParenteralNutritionPlan parenteralNutritionPlan) {
        parenteralNutritionPlanMapper.insert(parenteralNutritionPlan);
        return parenteralNutritionPlan.getNutritionPlanId();
    }

    @Override
    public int findNumberByTreatmentStage(int treatmentStage) {
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("treatmentStage", treatmentStage);
        List<Patient> patients = patientMapper.selectList(queryWrapper);
        return patients.size();
    }

    @Override
    public int findNumberByHospitalizationStage(int hospitalizationStage) {
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hospitalizationStage", hospitalizationStage);
        List<Patient> patients = patientMapper.selectList(queryWrapper);
        return patients.size();
    }


}
